package com.yxs.go_bang.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yxs.go_bang.game.MatchRequest;
import com.yxs.go_bang.game.MatchResponse;
import com.yxs.go_bang.game.Matcher;
import com.yxs.go_bang.game.OnlineUserManaage;
import com.yxs.go_bang.model.User;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class MatchAPI extends TextWebSocketHandler {

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private OnlineUserManaage onlineUserManaage;



    @Autowired
    private Matcher matcher;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("MatchAPI连接成功");
        // 维护用户上线
        // 因为注册 MatchAPI 到 WebSocketConfig时使用拦截器
        // .addInterceptors(new HttpSessionHandshakeInterceptor());
        // 这时websocketsession就可以得到httpsession中的用户信息了
        try {
            User user=(User) session.getAttributes().get("user");
            if (onlineUserManaage.getFromGameHall(user.getUserId())!=null ||
                    onlineUserManaage.getFromGameRoom(user.getUserId())!=null){
                MatchResponse matchResponse=new MatchResponse();
                matchResponse.setOk(true); // 意料之内的情况摄者为 true
                matchResponse.setReason("禁止多开！");
                matchResponse.setMessage("repeatConnection");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));
                //session.close(); 关闭连接去客服端处理
                return;
            }
            onlineUserManaage.enterGameHall(user.getUserId(),session);
            System.out.println(user.getUsername()+"进入游戏大厅");
        }catch (NullPointerException e){
            e.printStackTrace();
            MatchResponse matchResponse=new MatchResponse();

            matchResponse.setOk(false);
            matchResponse.setReason("您尚未登录，无法进行后续操作");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        User user=(User) session.getAttributes().get("user");
        // 获取客服端给服务器发送的数据
        String payload=message.getPayload();
        // 将上面的json字符串转换为自定义的 matchrequest Java对象
        MatchResponse matchResponse=new MatchResponse();
        MatchRequest matchRequest=objectMapper.readValue(payload, MatchRequest.class);
        if (matchRequest.getMessage().equals("startMatch")){
            // 进入匹配队列
            matcher.add(user);
            // 返回一个响应给客服端
            matchResponse.setOk(true);
            matchResponse.setMessage("startMatch");
        }else if (matchRequest.getMessage().equals("stopMatch")){
            // 退出匹配队列
            matcher.remove(user);
            // 响应客服端

            matchResponse.setOk(true);
            matchResponse.setMessage("stopMatch");
        }else {

            matchResponse.setOk(false);
            matchResponse.setReason("非法的匹配请求");
        }
        String respJson=objectMapper.writeValueAsString(matchResponse);
        session.sendMessage(new TextMessage(respJson));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("MatchAPI连接异常");
        // 玩家下线
        try {
            User user=(User) session.getAttributes().get("user");
            WebSocketSession tmpSession=onlineUserManaage.getFromGameHall(user.getUserId());
            if (tmpSession == session){
                onlineUserManaage.exitGameHall(user.getUserId());
            }
            // 如果连接断开或者出错，将在匹配队列里面的玩家移除
            matcher.remove(user);
        }catch (NullPointerException e){
            e.printStackTrace();
            System.out.println("当前用户未登录");

//            MatchResponse matchResponse=new MatchResponse();
//
//            matchResponse.setOk(false);
//            matchResponse.setReason("您尚未登录，无法进行后续操作");
//            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));
        }

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("MatchAPI连接关闭");
        // 玩家下线
        try {
            User user=(User) session.getAttributes().get("user");
            WebSocketSession tmpSession=onlineUserManaage.getFromGameHall(user.getUserId());
            if (tmpSession == session){
                onlineUserManaage.exitGameHall(user.getUserId());
            }
            // 如果连接断开或者出错，将在匹配队列里面的玩家移除
            matcher.remove(user);
        }catch (NullPointerException e){
            e.printStackTrace();
            System.out.println("当前用户未登录");

//            MatchResponse matchResponse=new MatchResponse();
//            matchResponse.setOk(false);
//            matchResponse.setReason("您尚未登录，无法进行后续操作");
//            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));
        }

    }
}
